#include <iostream>
using std::cout;
using std::endl;

class Stack {
   public:
    // 构造函数
    Stack(int maxSize = 10)  // 默认栈大小为10，用户可自己输入
    : _maxSize(maxSize)
    , _topIndex(-1)  // 默认栈顶元素索引为-1
    , _data(new int[maxSize]())  // 在堆上申请数组
    {
        cout << "调用构造函数创建栈" << endl;
    }

    // 判空
    bool empty() { return _topIndex == -1; }

    // 判满
    bool full() { return _maxSize - _topIndex == 1; }

    // 元素入栈
    void push(int val) {
        if (full()) {
            cout << "Stack is full!" << endl;
            return;
        } else {
            _data[_topIndex + 1] = val;
            ++_topIndex;
        }
    }

    // 元素出栈
    void pop() {
        if (empty()) {
            cout << "Stack is empty!" << endl;
            return;
        } else {
            --_topIndex;
        }
    }

    // 获取栈顶元素
    int top() {
        if (empty()) {
            cout << "Stack is empty!" << endl;
            return -1;
        } else {
            return _data[_topIndex];
        }
    }

    // 析构函数
    ~Stack() {
        if (_data) {
            delete[] _data;
            _data = nullptr;
        }
        cout << "调用析构函数" << endl;
    }

   private:
    int _topIndex;
    int _maxSize;
    int* _data;
};

int main(void) {
    Stack s1(3);
    cout << "栈大小为3" << endl;
    cout << "栈是否为空: " << s1.empty() << endl;
    cout << "栈是否为满: " << s1.full() << endl;
    cout << "----------" << endl;
    
    s1.push(2);
    cout << "2入栈" << endl;
    s1.push(6);
    cout << "6入栈" << endl;
    cout << "栈顶元素为: " << s1.top() << endl;
    cout << "栈是否为空: " << s1.empty() << endl;
    cout << "栈是否为满: " << s1.full() << endl;
    cout << "----------" << endl;
    
    s1.push(10);
    cout << "10入栈" << endl;
    cout << "栈顶元素为: " << s1.top() << endl;
    cout << "栈是否为空: " << s1.empty() << endl;
    cout << "栈是否为满: " << s1.full() << endl;
    cout << "继续入栈" << endl;
    s1.push(12);
    cout << "栈顶元素为: " << s1.top() << endl;
    cout << "栈是否为空: " << s1.empty() << endl;
    cout << "栈是否为满: " << s1.full() << endl;
    cout << "----------" << endl;
    
    s1.pop();
    cout << "出栈" << endl;
    cout << "栈顶元素为: " << s1.top() << endl;
    cout << "栈是否为空: " << s1.empty() << endl;
    cout << "栈是否为满: " << s1.full() << endl;
    cout << "----------" << endl;

    return 0;
}
